package com.lgCore.serverHandler;

import com.lgCore.common.LocalSession;
import com.lgCore.common.SessionManger;
import com.lgCore.constants.NettyServerConstants;
import com.lgCore.nettyCocurrent.ExecutorScheduler;
import com.lgCore.protoModel.ProtoMsg;
import com.lgCore.serverProcesser.HeartCallable;
import com.lgCore.serverProcesser.ServiceInvokCallable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * create by 尼恩 @ 疯狂创客圈
 **/
@Slf4j
public class HeartBeatServerHandler extends IdleStateHandler {
    private static final int READ_IDLE_GAP = 150;

    public HeartBeatServerHandler() {
        super(READ_IDLE_GAP, 0, 0, TimeUnit.SECONDS);

    }

    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
//        log.info( "接受数据"+ msg);
        //判断消息实例
        if (null == msg || !(msg instanceof ProtoMsg.Message)) {
            super.channelRead(ctx, msg);
            return;
        }
        ProtoMsg.Message message = (ProtoMsg.Message) msg;
        LocalSession session = SessionManger.get(message.getHeartRequest().getClientId());
        if (null == session) {
            super.channelRead(ctx, msg);
            return;
        }
        //发送心跳信息
//        LOGIN_REQUEST = 0;  //登录请求
//        LOGIN_RESPONSE = 1; //登录响应
//        LOGINOUT_REQUEST = 2;  //登出请求
//        LOGINOUT_RESPONSE = 3; //登出响应
//        HEART_REQUEST = 4;  //心跳请求
//        HEART_RESPONSE = 5; //心跳响应
//        RPC_REQUEST = 6;    //rpc请求
//        RPC_RESPONSE = 7;   //rpc响应
        if (ProtoMsg.HeadType.HEART_REQUEST_VALUE==message.getHeartRequest().getType().getNumber()) {
            //异步处理,将心跳包，直接回复给客户端
            if (ctx.channel().isActive()) {
                HeartCallable heartCallable = new HeartCallable(message,session);
//                FutureTaskScheduler.add(heartCallable);
                ExecutorScheduler.add(heartCallable);
            }
        }
        super.channelRead(ctx, msg);

    }

    @Override
    protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
        log.info(READ_IDLE_GAP + "秒内未读到数据，关闭连接",ctx.channel().attr(NettyServerConstants.channelID).get());
        // TODO: 2020/11/11  这里删除 netty连接，同时需要在netty管理那里处理
    }




}